using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using CsvHelper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Hosting;
using CaipuGuanliXitong.Models;
using SqlSugar;

namespace CaipuGuanliXitong.Controllers
{
    public class DatabaseController : Controller
    {
        private readonly CookBookDbContext _context;
        private readonly IWebHostEnvironment _environment;

        public DatabaseController(CookBookDbContext context, IWebHostEnvironment environment)
        {
            _context = context;
            _environment = environment;
        }

        public IActionResult Index()
        {
            // 获取所有已逻辑删除的数据
            var model = new DeletedItemsViewModel
            {
                DeletedCookBooks = _context.CookBooks.GetList(x => x.IsDeleted),
                DeletedIngredients = _context.Ingredients.GetList(x => x.IsDeleted),
                DeletedRecipeIngredients = _context.RecipeIngredients.GetList(x => x.IsDeleted),
                DeletedWeeklyMenus = _context.WeeklyMenus.GetList(x => x.IsDeleted),
                DeletedDailyPurchases = _context.DailyPurchases.GetList(x => x.IsDeleted)
            };
            
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult ReCreateDatabase()
        {
            try
            {
                _context.ReCreateDatabase();
                ViewBag.Message = "数据库表已成功重新创建！";
                ViewBag.IsSuccess = true;
            }
            catch (Exception ex)
            {
                ViewBag.Message = "重新创建数据库表时出错: " + ex.Message;
                ViewBag.IsSuccess = false;
            }

            return View("Index");
        }
        
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult BackupDatabase()
        {
            try
            {
                // 创建备份文件夹
                var backupFolder = Path.Combine(_environment.WebRootPath, "backups");
                if (!Directory.Exists(backupFolder))
                {
                    Directory.CreateDirectory(backupFolder);
                }
                
                // 生成备份文件名
                var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                var backupFileName = $"cookbook_backup_{timestamp}.zip";
                var backupFilePath = Path.Combine(backupFolder, backupFileName);
                
                // 创建临时文件夹用于存储数据
                var tempFolder = Path.Combine(Path.GetTempPath(), $"cookbook_backup_{timestamp}");
                Directory.CreateDirectory(tempFolder);
                
                try
                {
                    // 导出各表数据到CSV文件
                    ExportTableToCsv(_context.CookBooks.GetList(), Path.Combine(tempFolder, "cookbooks.csv"));
                    ExportTableToCsv(_context.Ingredients.GetList(), Path.Combine(tempFolder, "ingredients.csv"));
                    ExportTableToCsv(_context.RecipeIngredients.GetList(), Path.Combine(tempFolder, "recipeingredients.csv"));
                    ExportTableToCsv(_context.WeeklyMenus.GetList(), Path.Combine(tempFolder, "weeklymenus.csv"));
                    
                    // 创建ZIP文件
                    ZipFile.CreateFromDirectory(tempFolder, backupFilePath);
                    
                    // 提供文件下载
                    var fileBytes = System.IO.File.ReadAllBytes(backupFilePath);
                    return File(fileBytes, "application/zip", backupFileName);
                }
                finally
                {
                    // 清理临时文件夹
                    if (Directory.Exists(tempFolder))
                    {
                        Directory.Delete(tempFolder, true);
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = "备份数据库时出错: " + ex.Message;
                ViewBag.IsSuccess = false;
                return View("Index");
            }
        }
        
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult RestoreDatabase(IFormFile backupFile)
        {
            if (backupFile == null || backupFile.Length == 0)
            {
                ViewBag.Message = "请选择一个备份文件";
                ViewBag.IsSuccess = false;
                return View("Index");
            }
            
            try
            {
                // 创建临时文件夹用于解压文件
                var tempFolder = Path.Combine(Path.GetTempPath(), $"cookbook_restore_{DateTime.Now:yyyyMMdd_HHmmss}");
                Directory.CreateDirectory(tempFolder);
                
                try
                {
                    // 保存上传的文件
                    var uploadedFilePath = Path.Combine(tempFolder, backupFile.FileName);
                    using (var stream = new FileStream(uploadedFilePath, FileMode.Create))
                    {
                        backupFile.CopyTo(stream);
                    }
                    
                    // 解压文件
                    ZipFile.ExtractToDirectory(uploadedFilePath, tempFolder);
                    
                    // 按正确顺序导入数据（先导入主表，再导入关联表）
                    ImportTableFromCsv<CookBook>(Path.Combine(tempFolder, "cookbooks.csv"), 
                        data => {
                            var existing = _context.CookBooks.AsQueryable().Any(x => x.Id == data.Id);
                            if (existing)
                            {
                                data.IsDeleted = false; // 确保恢复的数据不是删除状态
                                _context.CookBooks.Update(data);
                            }
                            else
                            {
                                data.IsDeleted = false; // 确保新导入的数据不是删除状态
                                _context.CookBooks.Insert(data);
                            }
                        });
                    
                    ImportTableFromCsv<Ingredient>(Path.Combine(tempFolder, "ingredients.csv"), 
                        data => {
                            var existing = _context.Ingredients.AsQueryable().Any(x => x.Id == data.Id);
                            if (existing)
                            {
                                data.IsDeleted = false; // 确保恢复的数据不是删除状态
                                _context.Ingredients.Update(data);
                            }
                            else
                            {
                                data.IsDeleted = false; // 确保新导入的数据不是删除状态
                                _context.Ingredients.Insert(data);
                            }
                        });
                    
                    ImportTableFromCsv<RecipeIngredient>(Path.Combine(tempFolder, "recipeingredients.csv"), 
                        data => {
                            var existing = _context.RecipeIngredients.AsQueryable().Any(x => x.Id == data.Id);
                            if (existing)
                            {
                                data.IsDeleted = false; // 确保恢复的数据不是删除状态
                                _context.RecipeIngredients.Update(data);
                            }
                            else
                            {
                                data.IsDeleted = false; // 确保新导入的数据不是删除状态
                                _context.RecipeIngredients.Insert(data);
                            }
                        });
                    
                    ImportTableFromCsv<WeeklyMenu>(Path.Combine(tempFolder, "weeklymenus.csv"), 
                        data => {
                            var existing = _context.WeeklyMenus.AsQueryable().Any(x => x.Id == data.Id);
                            if (existing)
                            {
                                data.IsDeleted = false; // 确保恢复的数据不是删除状态
                                _context.WeeklyMenus.Update(data);
                            }
                            else
                            {
                                data.IsDeleted = false; // 确保新导入的数据不是删除状态
                                _context.WeeklyMenus.Insert(data);
                            }
                        });
                    
                    ViewBag.Message = "数据库恢复成功完成";
                    ViewBag.IsSuccess = true;
                }
                finally
                {
                    // 清理临时文件夹
                    if (Directory.Exists(tempFolder))
                    {
                        Directory.Delete(tempFolder, true);
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = "恢复数据库时出错: " + ex.Message;
                ViewBag.IsSuccess = false;
            }

            return View("Index");
        }
        
        // 批量真正删除选中的项目
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult PermanentlyDelete(string table, int[] ids)
        {
            try
            {
                if (ids == null || ids.Length == 0)
                {
                    ViewBag.Message = "未选择任何项目";
                    ViewBag.IsSuccess = false;
                    return RedirectToAction("Index");
                }

                switch (table)
                {
                    case "CookBook":
                        foreach (var id in ids)
                        {
                            _context.CookBooks.DeleteById(id);
                        }
                        break;
                    case "Ingredient":
                        foreach (var id in ids)
                        {
                            _context.Ingredients.DeleteById(id);
                        }
                        break;
                    case "RecipeIngredient":
                        foreach (var id in ids)
                        {
                            _context.RecipeIngredients.DeleteById(id);
                        }
                        break;
                    case "WeeklyMenu":
                        foreach (var id in ids)
                        {
                            _context.WeeklyMenus.DeleteById(id);
                        }
                        break;
                    case "DailyPurchase":
                        foreach (var id in ids)
                        {
                            _context.DailyPurchases.DeleteById(id);
                        }
                        break;
                }

                ViewBag.Message = $"已从 {table} 表中永久删除 {ids.Length} 个项目";
                ViewBag.IsSuccess = true;
            }
            catch (Exception ex)
            {
                ViewBag.Message = $"永久删除时出错: {ex.Message}";
                ViewBag.IsSuccess = false;
            }

            return RedirectToAction("Index");
        }

        // 批量取消删除选中的项目
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Undelete(string table, int[] ids)
        {
            try
            {
                if (ids == null || ids.Length == 0)
                {
                    ViewBag.Message = "未选择任何项目";
                    ViewBag.IsSuccess = false;
                    return RedirectToAction("Index");
                }

                switch (table)
                {
                    case "CookBook":
                        var cookBooks = _context.CookBooks.GetList(x => ids.Contains(x.Id));
                        foreach (var item in cookBooks)
                        {
                            item.IsDeleted = false;
                            item.UpdatedTime = DateTime.Now;
                            _context.CookBooks.Update(item);
                        }
                        break;
                    case "Ingredient":
                        var ingredients = _context.Ingredients.GetList(x => ids.Contains(x.Id));
                        foreach (var item in ingredients)
                        {
                            item.IsDeleted = false;
                            item.UpdatedTime = DateTime.Now;
                            _context.Ingredients.Update(item);
                        }
                        break;
                    case "RecipeIngredient":
                        var recipeIngredients = _context.RecipeIngredients.GetList(x => ids.Contains(x.Id));
                        foreach (var item in recipeIngredients)
                        {
                            item.IsDeleted = false;
                            item.UpdatedTime = DateTime.Now;
                            _context.RecipeIngredients.Update(item);
                        }
                        break;
                    case "WeeklyMenu":
                        var weeklyMenus = _context.WeeklyMenus.GetList(x => ids.Contains(x.Id));
                        foreach (var item in weeklyMenus)
                        {
                            item.IsDeleted = false;
                            item.UpdatedTime = DateTime.Now;
                            _context.WeeklyMenus.Update(item);
                        }
                        break;
                    case "DailyPurchase":
                        var dailyPurchases = _context.DailyPurchases.GetList(x => ids.Contains(x.Id));
                        foreach (var item in dailyPurchases)
                        {
                            item.IsDeleted = false;
                            item.UpdatedTime = DateTime.Now;
                            _context.DailyPurchases.Update(item);
                        }
                        break;
                }

                ViewBag.Message = $"已从 {table} 表中恢复 {ids.Length} 个项目";
                ViewBag.IsSuccess = true;
            }
            catch (Exception ex)
            {
                ViewBag.Message = $"恢复项目时出错: {ex.Message}";
                ViewBag.IsSuccess = false;
            }

            return RedirectToAction("Index");
        }
        
        private void ExportTableToCsv<T>(List<T> data, string filePath)
        {
            using var writer = new StreamWriter(filePath);
            using var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.InvariantCulture);
            csv.WriteRecords(data);
        }
        
        private void ImportTableFromCsv<T>(string filePath, Action<T> insertAction) where T : new()
        {
            if (!System.IO.File.Exists(filePath)) return;
            
            using var reader = new StreamReader(filePath);
            using var csv = new CsvHelper.CsvReader(reader, System.Globalization.CultureInfo.InvariantCulture);
            var records = csv.GetRecords<T>();
            
            foreach (var record in records)
            {
                insertAction(record);
            }
        }
    }
    
    // 已删除项目的视图模型
    public class DeletedItemsViewModel
    {
        public List<CookBook> DeletedCookBooks { get; set; } = new List<CookBook>();
        public List<Ingredient> DeletedIngredients { get; set; } = new List<Ingredient>();
        public List<RecipeIngredient> DeletedRecipeIngredients { get; set; } = new List<RecipeIngredient>();
        public List<WeeklyMenu> DeletedWeeklyMenus { get; set; } = new List<WeeklyMenu>();
        public List<DailyPurchase> DeletedDailyPurchases { get; set; } = new List<DailyPurchase>();
    }
}